import router from '@/router'
import {post} from '@/util/request'
import moment from 'moment'

export default {
	namespace:'announcementList',
	namespaced:true,
	state:{
		isLoading:false,
		isModalLoading:false,
		isSubmiting:false,
		pageData:{}
	},
	mutations:{
		changeLoading(state,v){
			state.isLoading = v;
		},
		changeModalLoading(state,v){
			state.isModalLoading = v;
		},
		changeSubmit(state,v){
			state.isSubmiting = v;
		},
		changePagedata(state,v){
			state.pageData = v;
		}
	},
	actions:{
		async reload({commit}, data) {
			commit('changeLoading',true);
			let res = await post('/base/announcement/list',data);
			res.data.data.thisPageElements.forEach((v,i) => {
				let msgContentStr = v.msgContent.length>15?v.msgContent.substring(0,15)+'...':v.msgContent;
        v.msgContentStr = msgContentStr;
				v.sendTimeStr = v.sendTime?moment(v.sendTime).format('YYYY-MM-DD HH:mm:ss'):'--';
      });
			commit('changePagedata',res.data.data);
			commit('changeLoading',false);
		},
		add({commit,state},form){
			commit('changeSubmit',true);
			return post('/base/announcement/addAnnouncement',form).then(data=>{
				commit('changeSubmit',false);
				return data;
			})
		},
		sendMsg({commit,state},id){
			commit('changeModalLoading',true);
			return post('/base/announcement/send',{id}).then(data=>{
				commit('changeModalLoading',false);
				return data;
			})
		}
	},
	subscriptions({dispatch},router){
		//给路由加监听一旦进入module绑定的页面时dispatch初始化action
		router.afterEach((to,from)=>{
			if(to.name === this.namespace){
				dispatch('reload',{})
			}
		})
	}
}
